﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Core
{
    public static class ViewMessage
    {
        public static void AddViewMessage(this Controller controller, string msg, ViewMessageType type)
        {
            AddViewMessage(controller, msg, "", type);
        }
        public static void AddViewMessage(this Controller controller, string msg, string msgContent, ViewMessageType type)
        {
            controller.Session.Add("ViewMessage", msg);
            controller.Session.Add("ViewMessageType", type);
            controller.Session.Add("ViewMessageContent", msgContent);
        }

        public static void AddViewMessage(this Controller controller, Exception ex)
        {
            if (ex.GetType() == typeof(ModelCheckException))
            {
                var McException = (ModelCheckException)ex;
                if (string.IsNullOrWhiteSpace(McException.Key))
                {
                    AddViewMessage(controller, ex.Message, ViewMessageType.Error);
                }
                controller.ModelState.AddModelError(McException.Key, McException.Message);
            }
            else
            {
                AddViewMessage(controller, ex.Message, ViewMessageType.Error);
            }

        }

        public static void AddViewMessage(this Controller controller, string msg)
        {
            AddViewMessage(controller, msg, ViewMessageType.Info);
        }

        public enum ViewMessageType
        {
            /// <summary>
            /// 错误
            /// </summary>
            Error,
            /// <summary>
            /// 信息
            /// </summary>
            Info,
            /// <summary>
            /// 警告
            /// </summary>
            Warning
        }
    }
}